package com.example.aircraftticketingsystemserver.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.aircraftticketingsystemserver.entity.Role;
import com.example.aircraftticketingsystemserver.entity.UserRole;
import com.example.aircraftticketingsystemserver.entity.User;
import com.example.aircraftticketingsystemserver.mapper.RoleMapper;
import com.example.aircraftticketingsystemserver.mapper.UserRoleMapper;
import com.example.aircraftticketingsystemserver.mapper.UsersMapper;
import com.example.aircraftticketingsystemserver.service.IUsersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lxz
 * @since 2024-08-05
 */
@Transactional
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, User> implements IUsersService {
    @Resource
    private UsersMapper usersMapper;
    @Resource
    private UserRoleMapper userRoleMapper;
    @Resource
    private RoleMapper roleMapper;
    @Override
    public User login(User user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", user.getUsername());
        queryWrapper.eq("password", user.getPassword());
        return usersMapper.selectOne(queryWrapper);
    }

    @Override
    public User getUserByToken(String token) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("token",token);
        User user = usersMapper.selectOne(queryWrapper);
        //通过用户id查询当前用户对应的角色列表
        QueryWrapper<UserRole> query=new QueryWrapper<>();
        query.eq("user_id", user.getUserId());
        List<UserRole> userRoles = userRoleMapper.selectList(query);
        List<Integer> roleIds = userRoles.stream().map(UserRole::getRoleId).collect(Collectors.toList());
        List<Role> roles = roleMapper.selectBatchIds(roleIds);
        System.out.println(roles);
        user.setRoles(roles);
        List<String> roleNames = roles.stream().map(Role::getRoleName).collect(Collectors.toList());
        user.setRoleNames(roleNames);
        return user;
    }

    @Override
    public User addUser(User user) {
        usersMapper.insert(user);
        return user;
    }


}
